import {
	PanelViewActionType,
	IPanelViewAbility,
	IParam,
	IViewActionResult,
} from '@/core/interface';
import { IPanelViewController } from '@/core/interface/view/controller';
import { IPanelViewControllerParams } from '@/core/interface/view/controller-params';
import { IPanelViewStore } from '@/core/interface/view/store';
import {
	IPanelAbility,
	ISearchFormAbility,
} from '@/core/interface/widgets/ability';
import { deepCopy } from '@/core/utils';
import { DEViewController } from './de-view-controller';

/**
 * 面板视图控制器
 *
 * @export
 * @class PanelViewController
 * @extends {ViewController}
 */
export class PanelViewController
	extends DEViewController<
		PanelViewActionType,
		IPanelViewStore,
		IPanelViewAbility
	>
	implements IPanelViewController<IPanelViewStore, IPanelViewAbility>
{
	/**
	 * 处理视图初始化
	 *
	 * @protected
	 * @param {IPanelViewControllerParams<PanelViewActionType, IPanelViewAbility>} params
	 * @memberof PanelViewController
	 */
	protected processViewInit(
		params: IPanelViewControllerParams<PanelViewActionType, IPanelViewAbility>
	) {
		super.processViewInit(params);
	}

	/**
	 * 获取面板部件能力
	 *
	 * @protected
	 * @return {*}  {(IPanelAbility | undefined)}
	 * @memberof PanelViewController
	 */
	protected getDECtrlAbility(): IPanelAbility | undefined {
		return this.getSubAbility<IPanelAbility>('panel');
	}

	/**
	 * 视图加载
	 *
	 * @param {IParam} [opts={}]
	 * @return {*}
	 * @memberof PanelViewController
	 */
	public viewMounted(opts: IParam = {}) {
		super.viewMounted(opts);
		if (this.model.useDefaultLayout) {
			if (!this.isLoadDefault) {
				this.isLoadDefault = true;
				return;
			}
			this.load();
		} else {
			this.initLayout().then(() => {
				this.load();
			});
		}
	}

	/**
	 * 视图加载
	 *
	 * @param {IParam} [args]
	 * @return {*}  {Promise<IViewActionResult>}
	 * @memberof PanelViewController
	 */
	public load(args?: IParam): Promise<IViewActionResult> {
		const panel = this.getSubAbility<IPanelAbility>('panel');
		const searchForm = this.getSubAbility<ISearchFormAbility>('searchForm');
		if (searchForm) {
			const tempViewParams = deepCopy(this.store.viewParams);
			return searchForm.loadDraft(tempViewParams);
		}
		if (panel) {
			const tempViewParams = deepCopy(this.store.viewParams);
			return panel.load(Object.assign(tempViewParams, args));
		} else {
			return Promise.reject({
				ok: false,
				data: null,
				rowData: { status: 500 },
			});
		}
	}
}
